﻿using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace BanZuiCloudControlAgent.Utils.Logging
{
    /// <summary>
    /// 日志管理器，负责管理日志记录器实例
    /// </summary>
    public static class LogManager
    {
        private static readonly Dictionary<string, Logger> _loggers = new Dictionary<string, Logger>();
        private static bool _initialized = false;
        private static readonly object _lockObject = new object();

        /// <summary>
        /// 初始化日志系统
        /// </summary>
        public static void Initialize()
        {
            if (_initialized)
                return;

            lock (_lockObject)
            {
                if (_initialized)
                    return;

                try
                {
                    // 初始化NLog配置
                    Logger.InitializeNLog();
                    
                    // 创建默认日志记录器（直接创建而不是通过GetLogger）
                    var defaultLogger = new Logger("Default");
                    _loggers["Default"] = defaultLogger;
                    
                    _initialized = true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"初始化日志系统失败: {ex.Message}");
                    throw;
                }
            }
        }

        /// <summary>
        /// 获取指定名称的日志记录器
        /// </summary>
        /// <param name="name">日志记录器名称</param>
        /// <returns>日志记录器</returns>
        public static Logger GetLogger(string name)
        {
            // 确保日志系统已初始化
            EnsureInitialized();

            lock (_loggers)
            {
                if (!_loggers.TryGetValue(name, out Logger logger))
                {
                    logger = new Logger(name);
                    _loggers[name] = logger;
                }
                return logger;
            }
        }
        
        /// <summary>
        /// 确保日志系统已初始化
        /// </summary>
        private static void EnsureInitialized()
        {
            if (!_initialized)
                Initialize();
        }

        /// <summary>
        /// 获取当前类的日志记录器
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <returns>日志记录器</returns>
        public static Logger GetCurrentClassLogger<T>()
        {
            return GetLogger(typeof(T).Name);
        }

        /// <summary>
        /// 获取当前类的日志记录器
        /// </summary>
        /// <returns>日志记录器</returns>
        public static Logger GetCurrentClassLogger()
        {
            StackFrame frame = new StackFrame(1, false);
            var method = frame.GetMethod();
            var declaringType = method?.DeclaringType;
            return GetLogger(declaringType?.Name ?? "Unknown");
        }

        /// <summary>
        /// 关闭日志系统
        /// </summary>
        public static void Shutdown()
        {
            NLog.LogManager.Shutdown();
        }
    }
} 